package me.zhanshi123.advancedcleaner.command;

import me.zhanshi123.advancedcleaner.Main;
import me.zhanshi123.advancedcleaner.command.type.AdminCommand;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;

import java.text.MessageFormat;

public class CommandsExecutor implements CommandExecutor {
    public boolean onCommand(CommandSender commandSender, Command command, String label, String[] args) {
        if (args.length == 0) {
            sendHelp(commandSender);
            return true;
        } else {
            String arg = args[0];
            SubCommand subCommand = Main.getInstance().getCommandHandler().getSubCommand(arg);
            if (subCommand == null) {
                subCommand = Main.getInstance().getCommandHandler().getSubCommand("*");
            }
            if (subCommand == null) {
                return true;
            }
            if (subCommand instanceof AdminCommand) {
                if (commandSender.isOp()) {
                    return handle(commandSender, command, label, args, subCommand);
                } else {
                    commandSender.sendMessage("§cYou don't have enough permission to do this");
                    return true;
                }
            } else {
                return handle(commandSender, command, label, args, subCommand);
            }
        }
    }

    private boolean handle(CommandSender commandSender, Command command, String label, String[] args, SubCommand subCommand) {
        if (subCommand.isNeedArg()) {
            int argLength = subCommand.getArgLength();
            if (argLength != args.length) {
                subCommand.sendHelp(commandSender);
                return true;
            } else {
                return subCommand.onCommand(commandSender, command, label, args);
            }
        } else {
            return subCommand.onCommand(commandSender, command, label, args);
        }
    }

    private void sendHelp(CommandSender sender) {
        Main.getInstance().getCommandHandler().getCommands().stream()
                .filter(subCommand -> !(subCommand instanceof AdminCommand))
                .filter(subCommand -> subCommand.getDescription() != null)
                .forEach(subCommand -> subCommand.sendHelp(sender));
        if (sender.isOp()) {
            Main.getInstance().getCommandHandler().getCommands().stream()
                    .filter(subCommand -> subCommand instanceof AdminCommand)
                    .forEach(subCommand -> subCommand.sendHelp(sender));
        }
    }
}
